package example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 发送延迟消息
 *
 * http://localhost:8080/ttl/sendMessage/%E5%98%BB%E5%98%BB
 */
@RestController
@RequestMapping("/ttl")
@Slf4j
public class SendMsgController {
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 开始发消息
    @GetMapping("sendMessage/{message}")
    public void sendMessage(@PathVariable String message){
        log.info("当前时间：{}，发送一条信息给两个队列：{}",new Date().toString(),message);
        // 发送一个延迟为10s的消息
        rabbitTemplate.convertAndSend("X", "XA", "消息来自 ttl 为 10S 的队列: "+message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自 ttl 为 40S 的队列: "+message);
    }

    // 开始发消息
    // http://localhost:8080/ttl/sendExpirationMsg/%E4%BD%A0%E5%A5%BD2/2000
    @GetMapping("sendExpirationMsg/{message}/{ttlTime}")
    public void sendMessage(@PathVariable String message,@PathVariable String ttlTime){
        log.info("当前时间：{}，发送一条时长{}毫秒TTL信息给队列QC：{}",new Date().toString(),ttlTime,message);
        // 发送一个延迟为10s的消息
        rabbitTemplate.convertAndSend("X", "XC", message,msg->{
            // 发送消息的时候 延迟时长
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
    }


    /**
     * http://localhost:8080/ttl/sendDelayMsg/come on baby1/20000
     * http://localhost:8080/ttl/sendDelayMsg/come on baby2/2000
     * @param message
     * @param delayTime
     */
    // 发送消息到延迟交换机
    @GetMapping("sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message,@PathVariable Integer delayTime) {
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_NAME, DELAYED_ROUTING_KEY, message,
                correlationData ->{
                    correlationData.getMessageProperties().setDelay(delayTime);
                    return correlationData;
                });
        log.info(" 当 前 时 间 ： {}, 发送一条延迟 {} 毫秒的信息给队列 delayed.queue:{}", new
                Date(),delayTime, message);
    }





}
